<?php
// +----------------------------------------------------------------------
// | ZengCMS [ 火火 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://zengcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 火火 <zengcms@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 附件控制器
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\facade\Config;
use app\member\service\User;
use app\common\annotation\NodeAnotation;
use app\common\annotation\ControllerAnnotation;
use app\admin\model\Attachment as Attachment_Model;
/**
 * @ControllerAnnotation(title="附件管理")
 * Class Attachment
 * @package app\admin\controller
 */
class Attachment extends Base
{
    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new Attachment_Model;
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $map = array();
        $query = array();
        $group_id = trim(input('group_id'));
        $file_type = trim(input('file_type'));
        $title = trim(input('title'));
        if ($group_id !== '') {
            $map[] = ['group_id', '=', $group_id];
            $query['group_id'] = $group_id;
        }
        if ($title) {
            $map[] = ['file_name|name', 'like', "%$title%"];
            $query['title'] = $title;
        }
        if ($file_type) {
            $map[] = ['file_type', '=', $file_type];
            $query['file_type'] = $file_type;
        }
        // ['query'=>$query] 可以改为 ['query'=>request()->param()] 方便多了
        $list = Db::name('attachment')->where($map)->order(['sort' => 'desc', 'id' => 'desc'])
        // ->paginate(['list_rows'=> sys_config('WEB_ONE_PAGE_NUMBER'),'var_page' => 'page','query' => $query])
        ->paginate(['list_rows'=> sys_config('WEB_ONE_PAGE_NUMBER'),'var_page' => 'page','query' => request()->param()])
        ->each(function ($item, $key) {
            if ($item['driver'] == 'local') { //本地
                $item['filevalue'] = $item['path'];
                $item['filepath'] = Config::get('view.tpl_replace_string.__STATIC__') . '/' . $item['path'];
            } else { //阿里云oss
                $item['filevalue'] = $item['path'];
                $item['filepath'] = $item['path'];
            }
            return $item;
        });
        $grouplist = Db::name('attachment_group')->select()->toArray();
        View::assign([
            'meta_title' => '文件管理',//标题
            'group_id' => $group_id,//分组id
            'grouplist' => $grouplist,//所有分组
            'file_type' => $file_type,//文件类型
            'list' => $list,//列表
        ]);
        // 记录当前列表页的cookie
        // cookie('__forward__', $_SERVER['REQUEST_URI']);
        return view();
    }
    /**
     * @NodeAnotation(title="附件选择")
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $_list = Attachment_Model::where($where)->where('file_type','image')->page($page, $limit)->order('id', 'desc')->select()->toArray();
            foreach($_list as $k=>$v){
                if($v['driver'] == 'local'){
                    $v['path'] = Config::get('view.tpl_replace_string.__STATIC__') . '/' . $v['path'];
                }
                $_list[$k] = $v;
            }
            $total = Attachment_Model::where($where)->order('id', 'desc')->count();
            $result = array("code" => 0, "count" => $total, "data" => $_list);
            return json($result);
        }
        return View::fetch();
    }
    /**
	 * @NodeAnotation(title="排序")
	 */
    public function sort($model = 'attachment', $data = array())
    {
        $data['sort'] = input('sort');
        return parent::sort($model, $data);
    }
    /**
     * @NodeAnotation(title="移动")
     */
    public function move()
    {
        $data = input('get.');
        if ($data['group_id'] && isset($data['ids'])) {
            $res = Db::name('attachment')
            ->where([['id', 'in', $data['ids']]])
            ->update(['group_id' => $data['group_id']]);
            if ($res) {
                return json(['code'=>1,'msg'=>'移动成功','url'=>'']);
            } else {
                return json(['code'=>0,'msg'=>'移动失败','url'=>'']);
            }
        } else {
            return json(['code'=>0,'msg'=>'请选择移动分组或要移动的文件','url'=>'']);
        }
    }
    /**
     * @NodeAnotation(title="裁剪图片")
     */
    public function cropper()
    {
        return View::fetch();
    }
    /**
     * @NodeAnotation(title="图片裁剪")
     */
    public function crop()
    {
        if (request()->isPost()) {
            $targ_w = $_POST['w'];
            $targ_h = $_POST['h'];
            if (!$targ_h && !$targ_w) {
                $this->error('请选择裁剪尺寸！');
            }
            $file_path = get_file_path(input('filevalue'),2);
            $file_info = getimagesize($file_path);
            $mime = $file_info['mime'];
            $mime_arr = explode('/', $mime);
            $ext = end($mime_arr);
            $name = basename($file_path);
            $file_name = md5((string) microtime(true)) . '.' . $ext;
            $dir = date('Ymd');
            mk_dirs(PROJECT_PATH . '/public/static/uploads/images/' . $dir);
            $newsrc = PROJECT_PATH . '/public/static/uploads/images/' . $dir . '/' . $file_name;
            // 创建源图的实例
            $img_r = imagecreatefromstring(file_get_contents($file_path));
            switch ($ext) {
                case 'png':
                    $jpeg_quality = 9; // 取值0-9
                    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
                    imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x1'], $_POST['y1'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                    header('Content-type: image/png');
                    imagepng($dst_r, $newsrc, $jpeg_quality);
                    break;

                case 'jpeg':
                    $jpeg_quality = 90; // 取值0-99
                    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
                    imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x1'], $_POST['y1'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                    header('Content-type: image/jpeg');
                    imagejpeg($dst_r, $newsrc, $jpeg_quality);
                    break;
                default:
                    $jpeg_quality = 90;
                    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
                    imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x1'], $_POST['y1'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                    header('Content-type: image/' . $ext);
                    $image_function = 'image' . $ext;
                    $image_function($dst_r, $newsrc, $jpeg_quality);
                    break;
            }
            // 判断图片是否已存在
            if ($file_exists = Attachment_Model::where('md5',hash_file('md5', $newsrc))->find()) {
                $filevalue = $file_exists['file_name'];
                @unlink($newsrc);
            }else{
                $data = [
                    'aid'         => UID,
                    'uid'         => 0,
                    'group_id'    => 0,
                    'file_name'   => $file_name,
                    'file_type'   => 'image',
                    'name'        => $name,
                    'module'      => app('http')->getName(),
                    'path'        => 'uploads/images/' . $dir . '/' . $file_name,
                    'thumb'       => '',
                    'url'         => '',
                    'mime'        => getimagesize($file_path)['mime'],
                    'ext'         => $ext,
                    'size'        => filesize($newsrc),
                    'md5'         => hash_file('md5', $newsrc),
                    'sha1'        => hash_file('sha1', $newsrc),
                    'status'      => 1,
                    'sort'        => 100,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                // 附件上传钩子，用于第三方文件上传扩展
                if (sys_config('upload_driver','local') != 'local') {
                    $hook_result = hook('UploadOss', $data, false);
                    $arr = json_decode($hook_result,true);
                    if($arr['code'] != 0){
                        $this->error($arr['info']);
                    }
                    $filevalue = $arr['path'];
                    @unlink($newsrc);
                }else{
                    if (Attachment_Model::create($data)) {
                        $filevalue = 'uploads/images/' . $dir . '/' . $file_name;
                    }else{
                        $this->error('裁剪失败！');
                    }
                }
            }
            View::assign(['filevalue'=>$filevalue]);
        }else{
            View::assign(['filevalue'=>'']);
        }
        return view('crop');
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function del()
    {
        $action = $this->request->get('action','');
        if($action == 'del') {
            $ids = $this->request->param('ids/a', null);
            if (empty($ids)) {
                $this->error('请选择需要删除的附件！');
            }
            if (!is_array($ids)) {
                $ids = array(0 => $ids);
            }
            foreach ($ids as $id) {
                try {
                    $this->modelClass->deleteFile($id);
                } catch (\Exception $ex) {
                    $this->error($ex->getMessage());
                }
            }
            $this->success('文件删除成功~');
        } elseif($action == 'delimg') {
            $url = input('url');
            $this->success('删除成功！');
        } elseif($action == 'kindeditor_image_del') { //kindeditor编辑器图片删除
            echo 1;die;
            if ($_POST["action"] == "delete") {
                $url = $_POST["url"];
                if (empty($url)) {
                    die(0);
                }
                $url = $_SERVER['DOCUMENT_ROOT'] . '/' . $url;
                if (file_exists($url)) {
                    $result = unlink($url);
                    if ($result) {
                        echo 1;
                    } else {
                        echo 0;
                    }
                } else {
                    echo 0;
                }
                exit();
            }
        }
    }
    /**
     * @NodeAnotation(title="下载附件")
     */
	public function download()
	{
        $id = input('id');
        $info = Db::name('attachment')->field('driver,path,name,ext')->where('id',$id)->find();
        if($info['driver'] == 'local'){
            $path = STATIC_PATH . '/' . $info['path'];
        }else{
            $path = PROJECT_PATH . '/public/static/uploads/temp/' . $info['name'];
            if (http_down($info['path'], $path) == false) {
                $this->error('下载失败！');
            }
        }
        $xpath = iconv('utf-8', 'gbk', $path);
        if (file_exists($xpath)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $info['name']);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length:' . filesize($xpath));
            ob_clean();
            flush();
            readfile($xpath);
            if($info['driver'] != 'local'){
                @unlink($xpath);
            }
            exit;
        }else{
            $this->error('附件不存在！');
        }
	}
    /**
     * @NodeAnotation(title="html代码远程图片本地化")
     */
    public function getUrlFile()
    {
        $content = $this->request->post('content');//html代码
        $type = $this->request->post('type');//文件类型
        $urls = [];
        preg_match_all("/(src|SRC)=[\"|'| ]{0,}((http|https):\/\/(.*)\.(gif|jpg|jpeg|bmp|png|tiff))/isU", $content, $urls);
        $urls = array_unique($urls[2]);
        $file_info = [
            'aid'=> (is_login()>0)?UID:0,
            'uid' => (is_login()<=0)?User::instance()->isLogin():0,
            'module' => 'admin',
            'thumb' => '',
        ];
        foreach ($urls as $vo) {
            $vo = trim(urldecode($vo));
            $host = parse_url($vo, PHP_URL_HOST);
            if ($host != $_SERVER['HTTP_HOST']) {
                // 当前域名下的文件不下载
                $fileExt = strrchr($vo, '.');
                if (!in_array($fileExt, ['.jpg', '.gif', '.png', '.bmp', '.jpeg', '.tiff'])) {
                    exit($content);
                }
                $filename = PROJECT_PATH . '/public/static/uploads/temp/' . md5($vo) . $fileExt;
                if (http_down($vo, $filename) !== false) {
                    $file_info['md5'] = hash_file('md5', $filename);
                    if ($file_exists = Attachment_Model::where(['md5' => $file_info['md5']])->find()) {
                        @unlink($filename);
                        if($file_exists['driver'] == 'local'){
                            $localpath = Config::get('view.tpl_replace_string.__STATIC__') . '/' . $file_exists['path'];
                        }else{
                            $localpath = $file_exists['path'];
                        }
                    } else {
                        $file_info['sha1'] = hash_file('sha1', $filename);
                        $file_info['size'] = filesize($filename);
                        $file_info['mime'] = mime_content_type($filename);
                        $fpath = $type . '/' . date('Ymd');
                        $savePath = PROJECT_PATH . '/public/static/uploads/' . $fpath;
                        if (!is_dir($savePath)) {
                            mkdir($savePath, 0755, true);
                        }
                        $fname = '/' . md5(microtime(true)) . $fileExt;
                        $file_info['group_id']  = 0;
                        $file_info['file_name'] = basename($fname);
                        $file_info['file_type'] = get_attachment_info($filename)['type'];
                        $file_info['name'] = basename($vo);
                        $file_info['path'] = 'uploads/' . str_replace('\\', '/', $fpath . $fname);
                        $file_info['url'] = '';
                        $file_info['ext'] = ltrim($fileExt, ".");
                        $file_info['status'] = 1;
                        $file_info['sort'] = 100;
                        $file_info['create_time'] = time();
                        $file_info['update_time'] = time();
                        if (rename($filename, $savePath . $fname)) {
                            Attachment_Model::create($file_info);
                            $localpath = Config::get('view.tpl_replace_string.__STATIC__') . '/' . $file_info['path'];
                        }
                    }
                    $content = str_replace($vo, $localpath, $content);
                }
            }
        }
        exit($content);
    }
}
